<script setup>
import { useResizeObserver } from '@vueuse/core'
import * as THREE from 'three'
import TWEEN from '@tweenjs/tween.js'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
import { getElementSize } from '@/views/study/three/composables'

const webgl = ref(null)

let renderer = null
let camera = null

onMounted(() => {
  const { width, height } = getElementSize(webgl)

  const scene = new THREE.Scene()
  camera = new THREE.PerspectiveCamera(30, width / height, 0.1, 1000)

  camera.position.set(25, 25, 25)
  camera.lookAt(0, 0, 0)

  const lights = []
  lights[0] = new THREE.DirectionalLight('#FFF', 5)
  lights[1] = new THREE.DirectionalLight('#FFF', 5)
  lights[2] = new THREE.DirectionalLight('#FFF', 5)

  lights[0].position.set(0, 200, 0)
  lights[1].position.set(100, 200, 100)
  lights[2].position.set(-100, -200, -100)

  scene.add(...lights)

  const geometry = new THREE.SphereGeometry(5, 50, 50)
  const material = new THREE.MeshPhongMaterial({
    color: '#156289',
  })

  const mesh = new THREE.Mesh(geometry, material)

  scene.add(mesh)

  renderer = new THREE.WebGLRenderer()
  renderer.setSize(width, height)
  renderer.render(scene, camera)
  webgl.value.appendChild(renderer.domElement)

  const orbit = new OrbitControls(camera, renderer.domElement)
  orbit.enableDamping = true

  // const pos = new THREE.Vector3()
  // mesh.getWorldPosition(pos)
  //
  // const pos2 = pos.clone().addScalar(50)
  //
  // new TWEEN.Tween({
  //   x: camera.position.x,
  //   y: camera.position.y,
  //   z: camera.position.z,
  //   tx: 0,
  //   ty: 0,
  //   tz: 0,
  // }).to({
  //   x: pos2.x,
  //   y: pos2.y,
  //   z: pos2.z,
  //   tx: pos.x,
  //   ty: pos.y,
  //   tz: pos.z,
  // }, 2000).onUpdate((obj) => {
  //   // 动态改变相机位置
  //   camera.position.set(obj.x, obj.y, obj.z)
  //   // 动态计算相机视线
  //   camera.lookAt(obj.tx, obj.ty, obj.tz)
  // }).start()

  // 相机圆周运动，且保持相机镜头对准坐标原点
  // const R = 50
  // new TWEEN.Tween({ angle: 0 }).to({ angle: Math.PI * 2 }, 16000).onUpdate((obj) => {
  //   camera.position.x = R * Math.cos(obj.angle)
  //   camera.position.z = R * Math.sin(obj.angle)
  //   camera.lookAt(0, 0, 0)
  // }).start()

  function render() {
    requestAnimationFrame(render)

    TWEEN.update()

    // orbit.update()

    renderer.render(scene, camera)
  }

  render()
})

function resizeHandler() {
  const { width, height } = getElementSize(webgl)

  camera.aspect = width / height
  camera.updateProjectionMatrix()

  renderer.setSize(width, height)
}

useResizeObserver(webgl, () => {
  resizeHandler()
})
</script>

<template>
  <div ref="webgl" />
</template>
